package cn.edu.scau.cmi.mengzhuorong.client;

import java.util.Scanner;
import cn.edu.scau.cmi.mengzhuorong.composite.consistent.*;
import java.lang.Runnable;

public class ConsistentCompositeClient implements Runnable {
	public static void main(String[] args) {
		String name,team;
		Team root = new Team("组织֯");
		System.out.println("树根：组织֯");
		Scanner reader = new Scanner(System.in);
		while(true) {
			System.out.println("请选择：1、增加个人  2、增加团体  3、删除团体/个人  0、退出");
			int choice = reader.nextInt();
			if(choice == 0) {
				System.exit(0);
			}
			switch(choice) {
			case 1:
			    System.out.print("请输入个人：");
		        name = reader.next();
		        System.out.print("请输入个人的父组织：");
		        team = reader.next();
		        safeAddChild(root,name,team,false);
		        break;
			case 2:
				System.out.print("请输入团队：");
			    name = reader.next();
			    System.out.print("请输入团队的父组织：");
			    team = reader.next();
			    safeAddChild(root,name,team,true);
			    break;
			case 3:
				System.out.print("请输入要删除的团队或个人：");
			    name = reader.next();
			    safeRemoveChild(root,name);
			    break;
			default:break;
			}
			safeDisplay(root,0);
		}
		
	}
	
	private static void safeAddChild(Team node,String child,String team,Boolean isTeam) {
		if(node.getName().equals(team)) {
			Organization newNode = isTeam ? new Team(child) : new Person(child);
			node.addChild(newNode);
			return ;
		}
		for(Organization children : node.getChildren()) {
			if(children instanceof Team) {
				safeAddChild((Team)children,child,team,isTeam);
			}
		}
	}
	
	private static void safeRemoveChild(Organization node,String name) {
		for(Organization child : ((Team)node).getChildren()) {
			if(child instanceof Person) {
				if(((Person) child).getName().equals(name)) {
					((Team)node).removeChild(child);
					return;
				}
			}
			else if(child instanceof Team) {
				if(((Team) child).getName().equals(name)) {
					((Team)node).removeChild(child);
					return;
				}
				safeRemoveChild(child,name);
			}
		}
	}
	
	private static void safeDisplay(Organization node,int level) {
		for(int i = 0; i < level; i++) {
			System.out.print(" ");
		}
		if(node instanceof Team) {
			String name = ((Team)node).getName();
			System.out.println(name + "{");
			for(int i = 0; i < level + name.length(); i++) {
				System.out.print(" ");
			}
			for(Organization child : ((Team)node).getChildren()) {
				safeDisplay(child,level + name.length());
			}
			
			for(int i = 0;i < level;i++) {
				System.out.print(" ");
			}
		System.out.println("}");
		}
		else if(node instanceof Person) {
			String name = ((Person)node).getName();
			for(int i = 0; i < level + name.length() + 2; i++) {
				System.out.print(" ");
			}
			System.out.println(name);

			
		}
		
	}
	
	@Override
	public void run() {
		this.main(null);
	}
}
